package com.tchintech.pay.net;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.utils.PropUtils;
import com.tchintech.pay.utils.Signature;


import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Administrator on 2017/7/27 0027.
 * okhttp传递表单数据
 */

public class OkhttpClientTest {


    //Post拼装URL
    public void path(Context context, Handler handler, String url, Map<String, String> map, int what) {
        String URL = PropUtils.getProp("config").getProperty("URL");
        url = URL + url;
        try {
            //JSONObject jsonObject = new JSONObject(map.toString());
            okhttpPost(context, handler, url, map, what);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void okhttpPost(Context context, Handler handler, String url, Map<String, String> json, int what) {

        if (!NetUtils.isNetworkConnected(context)) {
            //无网络连接直接返回空值
            handler.sendEmptyMessage(HttpCode.networkabnormal);
            System.out.println("无网络连接");
        } else {
            System.out.println("okhttp请求URL" + url);
            System.out.println("okhttp请求参数" + json.toString());
            postSync(handler, url, json, what);
        }
    }

    //post请求
    private void postSync(final Handler handler, final String url, final Map<String, String> map, final int what) {


        new Thread() {
            @Override
            public void run() {
                // 2. 构建要传输给服务器的参数
                //以json形式传递数据
                // RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                //以form表单来传递数据
                //  FormBody formBody = new FormBody.Builder().add("","").build();
                FormBody.Builder builder = new FormBody.Builder();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    builder.add(entry.getKey(), entry.getValue().toString());
                }

                Request request = new Request.Builder().url(url).post(builder.build()).build();
               // Request request = new Request.Builder().url(url).build();
                //设置超时时间   因为php服务的超时时间为10s这里考虑到网络原因 所以设置12s
                new OkHttpClient().newBuilder().connectTimeout(0, TimeUnit.SECONDS).writeTimeout(12, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
                Call call = new OkHttpClient().newCall(request);
                try {
                    // 5. 同步post请求服务器
                    Response response = call.execute();
                    // 6. 处理响应的结果
                    if (response.isSuccessful()) {
                        String reponseStr = response.body().string();
                        System.out.println("okhttp请求成功" + reponseStr);
                        String result = new String(reponseStr.getBytes(),"UTF-8");
                        Message message = new Message();
                        message.obj = result;
                        message.what = what;
                        handler.sendMessage(message);
                    } else {
                        //   Log.e(TAG, "同步Post请求失败 ===========, code = " + response.code());
                        System.out.println("okhttp请求失败");
                        handler.sendEmptyMessage(HttpCode.http_timeout);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(HttpCode.http_failed);
                }
            }
        }.start();
    }


    //get请求
    public void getSync(Context context,final Handler handler, final String url, final int what) {
        if (!NetUtils.isNetworkConnected(context)) {
            //无网络连接直接返回空值
            handler.sendEmptyMessage(HttpCode.networkabnormal);
            System.out.println("无网络连接");
            return;
        }
        new Thread() {
            @Override
            public void run() {
                // 2. 构建要传输给服务器的参数
                //以json形式传递数据
                // RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                //以form表单来传递数据
                //  FormBody formBody = new FormBody.Builder().add("","").build();
                Request request = new Request.Builder().url(url).build();
                //设置超时时间
                new OkHttpClient().newBuilder().connectTimeout(0, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
                Call call = new OkHttpClient().newCall(request);
                try {
                    // 5. 同步post请求服务器
                    Response response = call.execute();
                    // 6. 处理响应的结果
                    if (response.isSuccessful()) {
                        String reponseStr = response.body().string();
                        System.out.println("okhttp请求参数1" + reponseStr);
                        Message message = new Message();
                        message.obj = reponseStr;
                        message.what = what;
                        handler.sendMessage(message);
                    } else {
                        //   Log.e(TAG, "同步Post请求失败 ===========, code = " + response.code());
                        System.out.println("okhttp请求参数222" + response.toString());
                        handler.sendEmptyMessage(HttpCode.http_timeout);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(HttpCode.http_failed);
                }
            }
        }.start();
    }


}
